#include "QtUI/AddNewRootRequirementCommand.qth"
#include "QtUI/AddNewRootRequirementCommand.moh"
#include "QtUI/RequirementInformationDialog.qth"
#include "QtUI/RequirementInformationWidget.qth"
#include "QtUI/PackageUndoableCommands.qth"
#include "QtUI/QtUIConfigurationCenter.hpp"
#include "QtUI/QtUndoableCommand.hpp"
#include "Ctrl/ControlCenter.hpp"
#include "Ctrl/PackageController.hpp"
#include "Model/Package.hpp"
#include "Model/Requirement.hpp"
#include "Model/InvalidNameError.hpp"
#include <QtGui/QAction>
#include <QtGui/QMessageBox>

namespace QtUI
{

AddNewRootRequirementCommand::AddNewRootRequirementCommand( QAction* pBoundAction)
	: UICommandBase( pBoundAction)
	, Impl::ProjectRelatedCommandEnabler( pBoundAction)
{
}

// ---------------------------------------------------------------------------------------------------------------------

bool AddNewRootRequirementCommand::execute( bool checked /*= false*/)
{
	using namespace Model;
	using namespace Ctrl;

	Package* pParentPackage = ControlCenter::instance().packageController().currentPackage();
	if( NULL == pParentPackage)
	{
		pParentPackage = &ControlCenter::instance().prjController().controlledProject().rootPackage();
	}

	RequirementInformationDialog dlg;
	int result = dlg.exec();
	while( result != QDialog::Rejected)
	{
		try
		{
			std::string name = dlg.widget()->requirementName().toStdString();
			std::string statement = dlg.widget()->requirementStatement().toStdString();
			std::auto_ptr< Requirement> pNewRootRq( new Requirement( name, statement));
			QtUI::QtUndoableCommand* pNewCommand
				= QtUI::PackageUndoableCommands::createAddNewRootRequirementCommand( ControlCenter::instance(), pParentPackage, pNewRootRq.release());
			QtUI::QtUIConfigurationCenter::qtUIConfigCenter().undoStack()->push( pNewCommand);

			break;
		}
		catch( Model::InvalidNameError& e)
		{
			QMessageBox::critical(
				&dlg,
				tr( "Adding New Root Requirement", "Error message box title"),
				e.invalidName().empty() ? 
				tr( "The name of the requirement can't be empty.", "Error message for empty requirement name")
				:
			tr( "The name of the requirement is invalid.", "Error message for invalid requirement name"));
		}
		result = dlg.exec();
	}
	return result == QDialog.Accepted;
}
	
} // namespace QtUI
